package controllers.cms;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import models.cms.BlockDto;
import models.cms.PageDto;
import play.Logger;
import play.api.templates.Html;

public class TemplateResolver {
	
	public static Html render(PageDto page) throws CmsException {
		try {
			Class tpl = Class.forName("views.html.pages." + page.getLayout().getPath());
			Method render = tpl.getMethod("render", PageDto.class);
			return (Html) render.invoke(null, page);
		} catch (ClassNotFoundException e) {
			Logger.error(e.getMessage(),e);
			throw new CmsException(e);
		} catch (NoSuchMethodException e) {
			Logger.error(e.getMessage(),e);
			throw new CmsException(e);
		} catch (SecurityException e) {
			Logger.error(e.getMessage(),e);
			throw new CmsException(e);
		} catch (IllegalAccessException e) {
			Logger.error(e.getMessage(),e);
			throw new CmsException(e);
		} catch (IllegalArgumentException e) {
			Logger.error(e.getMessage(),e);
			throw new CmsException(e);
		} catch (InvocationTargetException e) {
			Logger.error(e.getMessage(),e);	
			throw new CmsException(e);
		}
	}

	public static Html render(PageDto page, BlockDto bloc) throws CmsException {
		try {
			Class tpl = Class.forName("views.html.blocks." + bloc.getTemplate().getPath());
			Method render = tpl.getMethod("render", PageDto.class, BlockDto.class);
			return (Html) render.invoke(null, page, bloc);
		} catch (ClassNotFoundException e) {
			Logger.error(e.getMessage(),e);
			throw new CmsException(e);
		} catch (NoSuchMethodException e) {
			Logger.error(e.getMessage(),e);
			throw new CmsException(e);
		} catch (SecurityException e) {
			Logger.error(e.getMessage(),e);
			throw new CmsException(e);
		} catch (IllegalAccessException e) {
			Logger.error(e.getMessage(),e);
			throw new CmsException(e);
		} catch (IllegalArgumentException e) {
			Logger.error(e.getMessage(),e);
			throw new CmsException(e);
		} catch (InvocationTargetException e) {
			Logger.error(e.getMessage(),e);	
			throw new CmsException(e);
		}
	}

}
